package com.ifacebox.web.quartz.job;

import com.ifacebox.web.admin.logger.service.TraceLoggerService;
import com.ifacebox.web.common.model.UserAgent;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.text.MessageFormat;

/**
 * @author znn
 */
public abstract class BaseJob implements Job {
    protected static final Logger logger = LoggerFactory.getLogger(BaseJob.class);
    @Resource
    private TraceLoggerService traceLoggerService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        UserAgent userAgent = new UserAgent(null);
        try {
            this.executeJob(jobExecutionContext);
        } finally {
            traceLoggerService.addTraceLogger(userAgent, "执行定时任务！【{} - {} - {}】"
                    , jobExecutionContext.getFireInstanceId()
                    , jobExecutionContext.getJobDetail().getKey().getName()
                    , MessageFormat.format("参数：{0} 运行时间：{1,date,yyyy-MM-dd HH:mm:ss} 本次运行时间：{2,date,yyyy-MM-dd HH:mm:ss} 上次运行时间：{3,date,yyyy-MM-dd HH:mm:ss} 下次运行时间：{4,date,yyyy-MM-dd HH:mm:ss}"
                            , jobExecutionContext.getMergedJobDataMap().getWrappedMap()
                            , jobExecutionContext.getScheduledFireTime()
                            , jobExecutionContext.getFireTime()
                            , jobExecutionContext.getPreviousFireTime()
                            , jobExecutionContext.getNextFireTime()));
        }
    }

    public abstract void executeJob(JobExecutionContext jobExecutionContext) throws JobExecutionException;
}
